import React from 'react';
import {withRouter} from 'react-router-dom';
import {Button, Checkbox, Dialog, Grid, Input, Message} from '@alifd/next';
import {
    FormBinder as IceFormBinder,
    FormBinderWrapper as IceFormBinderWrapper,
    FormError as IceFormError,
} from '@icedesign/form-binder';
import Icon from '@icedesign/foundation-symbol';
import styles from './index.module.scss';
import axios from 'axios';
import auth from '@/request'
import server from '@/server'
import $http from '@/service/Services';
import {headerMenuConfig} from '@/menuConfig';
import {craPassword} from "../../../common";


const {Row, Col} = Grid;
let form;
let uuid = "";

class UserLogin extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            codeUrl:"",
            visible: false,
            username: '',
            password: '',
            roles: []
        };
        this.uuid = "";
        this.$http = $http;
        this.server = server;
        this.url = auth.auth.url;
        this.formChange = this.formChange.bind(this);
        this.handleSubmit = this.handleSubmit.bind(this);
        this.onClose = this.onClose.bind(this);
        this.keypress = this.keypress.bind(this);
    }


    formChange = (formValue) => {
        this.state = formValue;
    };

    // 组件挂载之前
    componentWillMount = () => {
        const _this = this;
        _this.clearAllCookie();
        _this.getCaptchaImage();
    };


    /**
     * 获取验证码
     */
    getCaptchaImage = () => {
        const that = this;
        axios.get(this.url + "/v1/captcha/captchaImage")
            .then(function (response) {
                const {data} = response;
                if (data.code === 0) {
                    that.setState({
                        codeUrl: "data:image/gif;base64," + data.data.img,
                        uuid: data.data.uuid
                },()=>{
                        uuid = that.state.uuid
                    })
                } else {
                    Message.success("操作成功.");
                    that.getMetadataItemList();
                }
            })
            .catch(function (error) {
                Message.error(error.message);
            });
    };

    /**
     * 关闭弹框
     */
    onClose = () => {
        this.setState({
            visible: false
        });
    };


    /**
     * 提交登录
     * @param e
     */
    handleSubmit = (e) => {
        const that = this;
        e.preventDefault();
        form.validateAll((errors, values) => {
            if (errors) {
                console.log('errors', errors);
                return;
            }
            values.password = craPassword(values._password);
            values["uuid"] = uuid;
            delete values._password;
            axios.post(this.url + "/v1/login/webLogin", values)
                .then(function (response) {
                    const {data} = response;
                    that.getCaptchaImage();
                    if (data.code != 0) {
                        Message.warning(data.message);
                    } else {
                        const rolePermission = data.data.rolePermissionVOS.length > 0 ? data.data.rolePermissionVOS[0] : {};
                        if (rolePermission.userId === "3") {
                            that.setState({
                                token: data.data.token,
                                sign: data.data.sign
                            }, () => {
                                that.handleClick({
                                    userId: rolePermission.userId,
                                    roleId: rolePermission.roleId,
                                    roleInstanceId: rolePermission.roleInstanceId,
                                    sign: data.data.sign
                                });
                            });
                        } else {
                            // 只有一个管理角色时，默认直接选中跳转
                            if (data.data.rolePermissionVOS.length == 1) {
                                that.setState({
                                    token: data.data.token,
                                    sign: data.data.sign
                                }, () => {
                                    that.handleClick({
                                        userId: rolePermission.userId,
                                        roleId: rolePermission.roleId,
                                        roleInstanceId: rolePermission.roleInstanceId,
                                        sign: data.data.sign
                                    });
                                });
                            } else {
                                that.setState({
                                    roles: data.data.rolePermissionVOS,
                                    token: data.data.token,
                                    sign: data.data.sign
                                }, () => {
                                    // 默认角色为“超级管理员”
                                    that.setState({
                                        visible: true
                                    });
                                })
                            }
                        }
                    }

                })
                .catch(function (error) {
                    Message.error(error.message);
                });
        });

    };

    /**
     * 获取用户的授权
     * @param userVo
     * @param call
     */
    getUserAuth = (userVo, call) => {
        const _this = this;
        this.$http.get(this.url + '/v1/user/getUserRoleAuth/' + userVo.rolePermissionVO.roleInstanceId)
            .then(function (response) {
                const {data} = response;
                const auths = data.data;
                _this.server.saveUserAuth(userVo, auths);
                if (call && typeof call == 'function') {
                    call(auths);
                }
            })
            .catch(function (error) {
                Message.error(error.message);
            })
    };
    /**
     *
     * @param item
     */
    handleClick = (item) => {
        const that = this;
        item.sign = this.state.sign;
        axios.post(this.url + "/v1/user/authentication", item, {
            headers: {
                'Authorization': this.state.token
            }
        })
            .then(function (response) {
                const {data} = response;

                if (data.code !== 0) {
                    Message.warning(data.message);
                } else {
                    that.server.updateToken(data.data.token);
                    const userVo = data.data.userInfoVO;
                    sessionStorage.setItem("userInfoVO", JSON.stringify(data.data.userInfoVO));
                    that.getUserAuth(userVo, (auths) => {
                        that.setState({
                            visible: false
                        }, () => {
                            // // 获取当前用户应用Id

                            //优先处理有系统菜单权限
                            if (auths.length > 0) {
                                Message.success('登录成功');
                                //跳转到有权限的第一个项目
                                for (let i = headerMenuConfig.length - 1; i >= 0; i--) {
                                    const has = server.hasAuth(headerMenuConfig[i]);
                                    if (has) {
                                        that.props.history.push(headerMenuConfig[i].path);
                                    }
                                }
                            } else {
                                Message.error("您未指定任务系统操作，请联系管理员.");
                            }
                        });
                    });
                }

            })
            .catch(function (error) {
                console.error(error);
                Message.error(error.message);
            });
    };


    //清除所有cookie函数
    clearAllCookie = () => {
        // 清除Storage缓存数据
        localStorage.clear();
        sessionStorage.clear();

        let date = new Date();
        date.setTime(date.getTime() - 1);
        let keys = document.cookie.match(/[^ =;]+(?=\=)/g);
        // console.log("需要删除的cookie名字："+keys);
        if (keys) {
            for (var i = keys.length; i--;) {
                document.cookie = keys[i] + "=0; expire=" + date.toGMTString() + "; path=/";
            }
        }
    };


    keypress(e) {
        if (e.which !== 13) return;
        console.log('你按了回车键...')
    }

    /**
     * 获取code
     */
    getCode =()=>{
        this.getCaptchaImage();
    };

    render() {
        const {visible} = this.state;
        const mock = this.state.roles;
        return (
            <div>
                <div className={styles.formContainer} onKeyPress={this.keypress}>
                    <h4 className={styles.formTitle}>{'欢迎登录'}</h4>
                    <IceFormBinderWrapper
                        value={this.state.value}
                        onChange={this.formChange}
                        ref={formRef => form = formRef}
                    >
                        <div className={styles.formItems}>
                            <Row className={styles.formItem}>
                                <Col className={styles.formItemCol}>
                                    <Icon type="person" size="small" className={styles.inputIcon}/>
                                    <IceFormBinder name="account" required message="必填">
                                        <Input
                                            className={styles.nextInputSingle}
                                            maxLength={20}
                                            placeholder="用户名"
                                        />
                                    </IceFormBinder>
                                </Col>
                                <Col>
                                    <IceFormError name="account"/>
                                </Col>
                            </Row>

                            <Row className={styles.formItem}>
                                <Col className={styles.formItemCol}>
                                    <Icon type="lock" size="small" className={styles.inputIcon}/>
                                    <IceFormBinder name="_password" required message="必填">
                                        <Input
                                            className={styles.nextInputSingle}
                                            htmlType="password"
                                            placeholder="密码"
                                        />
                                    </IceFormBinder>
                                </Col>
                                <Col>
                                    <IceFormError name="password"/>
                                </Col>
                            </Row>
                            <Row className={styles.formItem}>
                                <Col className={styles.formItemCol}>
                                    <Icon type="lock" size="small" className={styles.inputIcon}/>
                                    <IceFormBinder name="code" required message="必填">
                                        <Input  size="small"
                                            className={styles.captchaImage}
                                            placeholder="验证码"
                                        />
                                    </IceFormBinder>
                                   <div style={{float: 'right'}}>
                                       <img src={this.state.codeUrl} onClick={() => this.getCode()} className={styles.loginCodeImg} alt={"点击更新"}/>
                                   </div>
                                </Col>
                                <Col>
                                    <IceFormError name="password"/>
                                </Col>
                            </Row>
                            <Row className={styles.formItem}>
                                <Col>
                                    <IceFormBinder name="checkbox">
                                        <Checkbox className={styles.checkbox}>记住账号</Checkbox>
                                    </IceFormBinder>
                                </Col>
                            </Row>

                            <Row className={styles.formItem}>
                                <Button
                                    type="primary"
                                    onClick={this.handleSubmit}
                                    className={styles.submitBtn}
                                >
                                    登 录
                                </Button>
                            </Row>

                            {/* <Row className={styles.tips}>
                                <Link to="/register" className={styles.tipsText}>
                                    立即注册
                                </Link>
                            </Row> */}
                        </div>
                    </IceFormBinderWrapper>
                    <Dialog
                        className='pipe-dialog'
                        title="确认登录"
                        visible={visible}
                        footerActions={[]}
                        onOk={this.onClose}
                        onCancel={this.onClose}
                        onClose={this.onClose}
                    >
                        <div className={styles.dContainer}>
                            <div className={styles.dCard}>
                                <h4 className={styles.dTitle}>角色列表</h4>
                                <div className={styles.dContent}>
                                    {mock.map((item, index) => {
                                        return (
                                            <div
                                                className={styles.dItem}
                                                key={index}
                                                onClick={this.handleClick.bind(this, item)}
                                            >
                                                <p className={styles.dItemTitle}>{item.roleName}</p>
                                            </div>
                                        );
                                    })}
                                </div>
                            </div>
                        </div>
                    </Dialog>
                </div>
            </div>
        );
    }
}

export default withRouter(UserLogin);
